﻿using DotNetDAL.DbStruct;
using DotNetDAL.Entity.DbStruct;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace DotNetDAL.Connector
{
   public class SqlServerCacheHelper
    {
        private SqlConnection conn { get; set; }
        public SqlServerCacheHelper(SqlConnection conn)
        {
            this.conn = conn;
        }

        /// <summary>
        /// 是否有表
        /// </summary>
        /// <param name="table_name"></param>
        /// <returns></returns>
        public bool IsExistTable(string table_name) {
            bool IsExist = CacheHelper.IsExistTableName(table_name);
            if (!IsExist)
            {
                SqlServerDbStructHelper dbsHelper = new SqlServerDbStructHelper(conn);
                List<string> tableList = dbsHelper.GetTableList();
                foreach(string table in tableList)
                {
                    CacheHelper.AddTableName(table);
                }
                IsExist = CacheHelper.IsExistTableName(table_name);
            }
            return IsExist;
        }
        /// <summary>
        /// 清除表结构
        /// </summary>
        /// <param name="table_name"></param>
        public void ClearTableStruct(string table_name)
        {
            CacheHelper.ClearTableStruct(table_name);
        }
        /// <summary>
        /// 获取表结构
        /// </summary>
        /// <param name="table_name"></param>
        /// <returns></returns>
        public DbStructColumnCache GetDbStructColumns(string table_name)
        {
            if (!IsExistTable(table_name))
            {
                throw new Exception("不存在表 "+table_name);
            }
            DbStructColumnCache cacheData = new DbStructColumnCache() {
                table_name= table_name
            };
            cacheData.columns = CacheHelper.GetTableStruct(table_name);
            if(cacheData.columns.Count == 0)
            {
                SqlServerDbStructHelper dbsHelper = new SqlServerDbStructHelper(conn);

                cacheData.columns = Utils.UtilPackage.CopyList<DbStructColumn, DbStructColumnDTO>(dbsHelper.GetDbStructColumnList(table_name));
                if (cacheData.columns.Count > 0)
                {
                    CacheHelper.SetTableStruct(table_name, cacheData.columns);
                }

            }
            return cacheData;
        }
        



    }
}
